package com.toogu.mazhangmen.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.toogu.mazhangmen.bean.SockReturnBean;
import com.toogu.mazhangmen.ui.login.LoginActivity;
import com.toogu.mazhangmen.util.EquipmentUtil;
import com.toogu.mazhangmen.util.OkhttpUtil;
import com.toogu.mazhangmen.util.TokenUtil;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class SockService extends Service {
    private WebSocket mWebSocket;//webSock

    private  Timer mTimer;

    private Queue<SockReturnBean> takePhotoQueue;
    private Queue<SockReturnBean> getHelpQueue;

    private Handler handler;

    private boolean isClosing;
    private SockService.OnProgressListener takePhotoListener;
    private SockService.OnProgressListener getHelpListener;

    public SockService() {
    }

    //定义接口
    public interface OnProgressListener{
        void onSockCallbackProgress(Queue<SockReturnBean> queue);
    }

    //设置binder
    public class SockBinder extends Binder {
        //设置接口
        public void getHelp(SockService.OnProgressListener listener) {
            getHelpListener=listener;
        }
        public void takePhoto(String sendMessage, SockService.OnProgressListener listener){
            takePhotoListener=listener;
            if(mWebSocket!=null) mWebSocket.send(sendMessage);
        }
        public void onUnbind(int isHelp){
            if(isHelp==0) takePhotoListener=null;
            else getHelpListener=null;
        }
    }

    @Override
    public void onDestroy() {
        Log.d("websock", "onDestroy: ");
        if(mTimer!=null) mTimer.cancel();
        if(mWebSocket!=null)mWebSocket.close(1000,"Close");
        super.onDestroy();
    }

    //绑定
    @Override
    public IBinder onBind(Intent intent) {
        return new SockBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    //只运行一次
    @Override
    public void onCreate() {
        Log.d("websock", "onCreate: ");
        super.onCreate();
        isClosing=false;
        takePhotoQueue= new LinkedList<>();
        getHelpQueue=new LinkedList<>();
        handler = new Handler(Looper.getMainLooper());
    }
    //每次调用startService都调用一次
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("websock", "onStartCommand: ");
        OkhttpUtil.getOkhttpUtil().webSock(webSocketListener);
        return super.onStartCommand(intent, flags, startId);
    }

    private void startTask(){
        JsonObject webSock=new JsonObject();
        webSock.addProperty("phonenum", "help@"+new TokenUtil().getId());
        webSock.addProperty("messagetype", "ping");

        mTimer= new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                if(mWebSocket == null) return;
                mWebSocket.send(webSock.toString());
            }
        };
        mTimer.schedule(timerTask, 0, 30000);
    }

    //WebSock的监听
    private WebSocketListener webSocketListener= new WebSocketListener() {
        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            super.onOpen(webSocket, response);
            Log.d("websock", "onOpen: "+response.toString());
            mWebSocket=webSocket;
            startTask();
        }

        @Override
        public void onMessage(WebSocket webSocket, String text) {
            super.onMessage(webSocket, text);
            Log.d("websock", "onMessage: "+text);
//            getHelpQueue.offer(new Gson().fromJson("{\"parkid\":\"1\",\"doorid\":\"1\"}",SockReturnBean.class));
            SockReturnBean sockReturnBean = new Gson().fromJson(text, SockReturnBean.class);
                switch (sockReturnBean.getMessagetype()){
                    case "ack":
                        break;
                    case "help":
                        EquipmentUtil.setHelp(sockReturnBean);
                        getHelpQueue.offer(sockReturnBean);
                        break;
                    case "1"://抓拍
                        takePhotoQueue.offer(sockReturnBean);
                        break;
                    default:
                        break;
                }
            if(getHelpListener!=null) getHelpListener.onSockCallbackProgress(getHelpQueue);
            if(takePhotoListener!=null) takePhotoListener.onSockCallbackProgress(takePhotoQueue);
        }
        @Override
        public void onMessage(WebSocket webSocket, ByteString bytes) {
            super.onMessage(webSocket, bytes);
            Log.d("websock", "onMessage: "+bytes);
        }
        @Override
        public void onClosing(WebSocket webSocket, int code, String reason) {
            super.onClosing(webSocket, code, reason);
            Log.d("websock", "onClosing: "+reason);
            if(reason.equals("Bye")){
                isClosing=true;
                handler.post(()->Toast.makeText(getApplicationContext(),"号码在另一个设备上登录",Toast.LENGTH_SHORT).show());
                new TokenUtil().setClear();
                Intent intent = new Intent(SockService.this, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                mTimer.cancel();
            }
            else if(reason.equals("Close")){
                isClosing=true;
            }

        }
        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            super.onClosed(webSocket, code, reason);
            Log.d("websock", "onClosed: "+reason);
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
            super.onFailure(webSocket, t, response);
            Log.d("websock", "onFailure: "+response);
            if(!isClosing) OkhttpUtil.getOkhttpUtil().webSock(webSocketListener);
        }
    };

}